package com.baoer.controller;

import cn.hutool.core.lang.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author: YING
 * @CreateTime: 2025-06-26
 * @Description:
 * @Version: 1.0
 */



public class AvatarUtil {

    @Value("${avatar.upload-dir}")
    private static String uploadPath;

    // 头像上传接口

    public static ResponseEntity<String> uploadAvatar(Integer userId, MultipartFile file) {

        try {
            // 1. 创建存储目录（如果不存在）
            Path uploadDir = Paths.get(uploadPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 2. 生成唯一文件名（防止覆盖）
            String originalFileName = file.getOriginalFilename();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + fileExtension;

            // 3. 保存文件
            Path filePath = Paths.get(uploadPath + newFileName);
            Files.copy(file.getInputStream(), filePath);

            // 4. 返回访问URL（实际应用中应保存到数据库）
            String accessUrl = "/avatars/" + newFileName;

            // TODO: 这里应该把 accessUrl 更新到用户表的avatar字段
            return ResponseEntity.ok(accessUrl);

        } catch (IOException e) {
            return ResponseEntity.internalServerError()
                    .body("头像上传失败：" + e.getMessage());
        }
    }

    // 头像删除接口
    @DeleteMapping("/delete")
    public ResponseEntity<String> deleteAvatar(
            @RequestParam("userId") Long userId,
            @RequestParam("avatarUrl") String avatarUrl) {

        try {
            // 1. 从URL中提取文件名
            String fileName = avatarUrl.substring(avatarUrl.lastIndexOf("/") + 1);

            // 2. 构建文件路径
            Path filePath = Paths.get(uploadPath + fileName);

            // 3. 删除文件
            if (Files.exists(filePath)) {
                Files.delete(filePath);

                // TODO: 这里应该把用户表的avatar字段设为null或默认头像
                return ResponseEntity.ok("头像删除成功");
            }

            return ResponseEntity.notFound().build();
        } catch (IOException e) {
            return ResponseEntity.internalServerError()
                    .body("头像删除失败：" + e.getMessage());
        }
    }
}